package ru.fadeev.crammer.ui;

import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;


/**
 * CrammerToolbarToggleButton represents custom toggle button 
 * with custom toggle border
 * @author Konstantin Fadeyev
 *
 */
public class CrammerToolbarToggleButton extends JToggleButton 
		implements MouseListener, ItemListener{
	protected Border raisedBorder;
	protected Border loweredBorder;
	protected Border inactiveBorder;

	protected boolean mouseButtonPressed;
	protected boolean inTheBorders;
	
	
	
	public CrammerToolbarToggleButton(Icon icon, String toolTip) {
		super(icon);
		setRolloverIcon(icon);
		setToolTipText(toolTip);
		setFocusable(false);
		
		Border outerRaisedBorder = new CrammerBevelBorder(BevelBorder.RAISED);
		Border innerRaisedBorder = new EmptyBorder(3, 3, 3, 3);
		raisedBorder = BorderFactory.createCompoundBorder(outerRaisedBorder, 
				innerRaisedBorder);
		Border outerLoweredBorder = new CrammerBevelBorder(BevelBorder.LOWERED);
		Border innerLoweredBorder = new EmptyBorder(3, 3, 3, 3);
		loweredBorder = BorderFactory.createCompoundBorder(outerLoweredBorder, 
				innerLoweredBorder);
		inactiveBorder = new EmptyBorder(4, 4, 4, 4);	 
		
		mouseButtonPressed = false;
		inTheBorders = false;
		
	    setBorder(inactiveBorder);
	    addMouseListener(this);
	    addItemListener(this);
	    setBorderPainted(true);
	}

	public void mousePressed(MouseEvent e) {
		if(isEnabled()) {
			mouseButtonPressed = true;
			setBorder(loweredBorder);
		}
	}

	public void mouseReleased(MouseEvent e) {
		if(isEnabled()) {
			if(mouseButtonPressed && inTheBorders) {
				if(isSelected()) {
					setBorder(loweredBorder);
				} else {
					setBorder(raisedBorder);
				}
			}
			mouseButtonPressed = false;
		}
	}

	public void mouseClicked(MouseEvent e) {
	}

	public void mouseEntered(MouseEvent e) {
		if(isEnabled()) {
			inTheBorders = true;
			if(!isSelected()) {
				if(mouseButtonPressed) {
					setBorder(loweredBorder);
				} else {
					setBorder(raisedBorder);
				}
			}	
		}
	}
	
	public void mouseExited(MouseEvent e) {
		if(isEnabled()) {
			inTheBorders = false;
			if(!isSelected()) {
				setBorder(inactiveBorder);
			} else {
				setBorder(loweredBorder);
			}
		}
	}
	
	public void itemStateChanged(ItemEvent e) {
		if(isSelected()) {
			setBorder(loweredBorder);
		} else {
			setBorder(inactiveBorder);
		}
	}
}
